<style lang="less" scoped>
@import "@/assets/style/variables.less";



.banner {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: @border-radius;
    box-shadow: @box-shadow;
    padding: @padd;
    transition: all 1s ease-in-out;
    animation: move 1s ease-in-out;

    .banner-form {
        margin-top: 15px;
    }

    .banner-form,
    .banner-table {
        margin-top: 20px;

        .opt {
            margin-bottom: 15px;
        }

        .preview-img {
            width: 360px;
            height: 180px;
        }

        .el-upload-list {
            display: none;
        }


    }


}

.my-input {
    height: 28px;
    line-height: 28px;
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border: 1px solid #DCDFE6;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 15px;
    transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
    width: 100%;
    border-radius: 4px;
}
</style>
<template>
    <div class="banner">

        <div class="banner-header">
            <el-button size="small" :type="num == 1 ? 'danger' : ''" @click="num = 1">发布广告</el-button>
            <el-button size="small" :type="num == 2 ? 'danger' : ''" @click="num = 2">广告列表</el-button>
        </div>

        <div v-if="num == 1" class="banner-form">
            <div class="opt">
                <el-input v-model="banner.title" placeholder="请输入广告标题"></el-input>
            </div>
            <div class="opt">
                <el-input v-model="banner.link" placeholder="请输入广告链接"></el-input>
            </div>
            <div class="opt" style="display: flex;">
                <el-upload class="upload-demo" drag action="" :on-change="changeFn" :autoUpload="false">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>

                <div v-if="src" class="opt-right" style="text-align: center; margin-left: 15px">
                    <img class="preview-img" :src="src" alt="">
                </div>
            </div>
            <div class="opt">
                <el-button type="primary" @click="submitBannerFn">点击发布</el-button>
            </div>
        </div>
        <div v-if="num == 2" class="banner-table">
            <el-table border :data="tableData"
                style="width: 100%;box-shadow:  0 0 5px rgba(0,0,0,.1); border-radius: 5px;">
                <el-table-column align="center" label="序号" width="80">
                    <template slot-scope="scope">
                        <span>{{ scope.$index + 1 }}</span>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="ID" prop="id" width="80"></el-table-column>

                <el-table-column align="center" label="标题" prop="banner_title" width="80"></el-table-column>

                <el-table-column align="center" label="链接">
                    <template slot-scope="scope">
                        <a :href="scope.row.banner_link" target="_blank">地址:({{ scope.row.banner_link }})</a>
                    </template>
                </el-table-column>


                <el-table-column align="center" label="图片">
                    <template slot-scope="scope">
                        <div class="demo-image__preview">
                            <el-image style="width: 150px; height: 100px" :src="scope.row.src"
                                :preview-src-list="[scope.row.src]">
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="right">
                    <template slot="header">
                        <input type="text" placeholder="关键字" class="my-input" v-model="search">
                        <!-- <el-input size="mini" placeholder="输入关键字搜索" autocomplete="true" /> -->
                    </template>
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div>
            <el-dialog title="修改广告" :visible.sync="centerDialogVisible" width="30%" center>
                <div>
                    <div class="opt">
                        <el-input v-model="title" placeholder="请输入广告标题"></el-input>
                    </div>

                    <div class="opt" style="margin: 15px 0px;">
                        <el-input v-model="link" placeholder="请输入广告链接"></el-input>
                    </div>
                    <div class="opt">
                        <img style="width: 100%" v-if="imgUrl" :src="imgUrl">
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="modifyBannerFn">保存修改</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
// 导入api
import { Message, MessageBox } from 'element-ui';
import { uploadPhoto, publishBanner, listBanner, removeBanner, removePhoto, searchBanner, modifyBanner, host } from '../api/index'


export default {
    data() {
        return {
            centerDialogVisible: false,
            banner: {
                title: "",
                link: ""
            },
            src: "",
            tableData: [
                //    {
                //     id:1,
                //     banner_title:"",
                //     banner_link:"",
                //     src:""
                //    }
            ],
            search: '',// 用于获取输入框的值
            num: 2,
            file: null,
            title: "",//记录修改的标题
            link: "",//记录修改的链接
            imgUrl: "",//记录修改的图片
            id: "",//广告的唯一标记
            picUrl: "",//   /static/imgs/1.jpg

            timer: null
        }
    },
    methods: {
        // 编写搜索方法
        async searchBannerFn(kw) {
            if (kw == "") {
                this.listBannerFn();
                return false;
            }
            await searchBanner({ keyword: kw })
                .then(
                    resData => {
                        // console.log("搜索：",resData)
                        if (resData.code == 200) {

                            if (resData.result.length > 0) {
                                // 解构赋值
                                let { result } = resData;
                                let newArr = result.map(item => {
                                    item.src = host + item.banner_url
                                    return item;
                                })
                                // console.log(newArr);
                                // 赋值用户界面跟着变化
                                this.tableData = newArr;
                                Message({
                                    showClose: true,
                                    message: "搜索成功",
                                    type: 'success',
                                    offset: 100
                                })
                            } else {
                                Message({
                                    showClose: true,
                                    message: "暂无该数据",
                                    type: 'error',
                                    offset: 100
                                })
                            }

                        }
                    }, err => {
                        console.log(err)
                        Message({
                            showClose: true,
                            message: "暂无该数据",
                            type: 'error',
                            offset: 100
                        })
                    }
                )
        },
        // 删除轮播图
        async removeBannerFn(row) {
            MessageBox.confirm("您确定要删除该记录吗?")
                .then(
                    async () => {
                        await removeBanner({ id: row.id })
                            .then(
                                resData => {
                                    // console.log(resData)
                                    if (resData.code == 200) {
                                        // 重新获取列表
                                        this.listBannerFn();

                                        if (row.banner_url == undefined) return false;
                                        // console.log(row.banner_url);
                                        // 再删除轮播图的图片文件
                                        removePhoto({ picUrl: row.banner_url }).then(() => {
                                        })
                                        // removePhoto({ picUrl: row.banner_url }).then((resData) => {
                                        //     console.log(resData)
                                        // })


                                    }
                                }
                            )


                    },

                )
                .catch(
                    () => {
                    }
                )

        },
        // 获取轮播图列表
        async listBannerFn() {
            await listBanner().then(
                resData => {
                    // console.log(resData);
                    if (resData.code == 200) {
                        // 解构赋值
                        let { result } = resData;
                        let newArr = result.map(item => {
                            item.src = host + item.banner_url
                            return item;
                        })
                        // console.log(newArr);
                        // 赋值用户界面跟着变化
                        this.tableData = newArr;
                    }
                },
                err => {
                    console.log(err)
                }
            )
        },
        // 点击发布
        async submitBannerFn() {
            if (this.banner.title == '' || this.banner.link == '') {
                Message({
                    type: 'error',
                    message: "输入框不能为空",
                    offset: 100,
                    showClose: true
                })
                return false;
            }
            if (this.src == '') {
                Message({
                    type: 'error',
                    message: "请上传图片",
                    offset: 100,
                    showClose: true
                })
                return false;
            }
            let result = await this.uploadPhotoFn()
            // console.log(result);
            // 发布轮播图
            await publishBanner({
                banner_title: this.banner.title,
                banner_link: this.banner.link,
                banner_url: result.picUrl// "/static/resources/imgs/photo-20251017-1760685486619.jpeg"
            })
                .then(
                    resData => {
                        // console.log(resData)
                        if (resData.code == 200) {
                            // 更新列表
                            this.listBannerFn();
                            this.num = 2;// 显示轮播图列表
                            // 重置表单
                            this.banner.title = "";
                            this.banner.link = "";
                            this.src = "";
                            this.file = null;
                            Message({
                                type: 'success',
                                message: "添加成功",
                                showClose: true,
                                offset: 100
                            })
                        }
                    },
                    err => {
                        console.log(err)
                    }
                )

        },
        // 上传图片
        async uploadPhotoFn() {
            // 采集信息的构造函数
            let formData = new FormData()
            formData.append('photo', this.file)
            return await uploadPhoto(formData)
        },
        // 预览图片
        changeFn(info) {
            // console.dir(info);// 图片信息对象
            // 读取单个文件
            let file = info.raw;
            const reader = new FileReader();
            reader.onload = () => {
                // 将图像文件转换为 Base64 字符串
                //  console.log(reader.result);
                this.src = reader.result;
            }
            if (file) {
                // 记录图片信息
                this.file = file;
                reader.readAsDataURL(file);
            }
            return false;
        },

        // 保存修改
        async modifyBannerFn() {
            let banner_title = this.title;
            let banner_link = this.link;
            let banner_url = this.picUrl;
            let id = this.id;
            await modifyBanner({ banner_title, banner_link, banner_url, id }).then(
                resData => {
                    // console.log(resData);
                    if (resData.code == 200) {
                        this.listBannerFn();
                        this.centerDialogVisible = false;
                        Message({
                            type: "success",
                            message: "修改成功"
                        })
                    }
                }
            )
        },
        // 编辑
        handleEdit(index, row) {
            // console.log(index, row);
            // 显示对话框
            this.centerDialogVisible = true;
            // 记录当前广告的信息
            this.title = row.banner_title;
            this.link = row.banner_link;
            this.imgUrl = row.src;// src 是完整的路径
            this.picUrl = row.banner_url;// banner_url 不是是完整的路径
            this.id = row.id;
        },
        // 删除
        async handleDelete(index, row) {
            // console.log(index, row);
            // 删除轮播图的方法
            if (row.id) {
                await this.removeBannerFn(row);// 删除记录
            }

        }
    },
    // 初始化
    created() {
        // 获取轮播图列表
        this.listBannerFn();

    },
    watch: {
        $route: {
            immediate: true,
            deep: true,
            handler(newRoute) {
                // console.log(newRoute);
                this.$store.commit("addTab", newRoute);
            }
        },
        // 观察输入框的变化
        search: function (newKeyword) {
            if (newKeyword.trim() == '') {
                this.listBannerFn()
                return
            }
            if (this.timer) {
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                this.searchBannerFn(newKeyword)
            }, 600)
        }
    }
}
</script>